﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO.IsolatedStorage;
using System.IO;

namespace FallingSand
{
    public partial class GamePage : PhoneApplicationPage
    {
        UIElementRenderer elementRenderer;

        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        private Grid _grid;

       

        Random _rand = new Random(50);

        private Rectangle _bucket = new Rectangle(240, 400, 40, 40);

        private int _nextPointGoal = 100;
        private Texture2D[] _bucketTexture = new Texture2D[6];
        private int _bucketTextureIndex = 0;

        private int _points = 0;

        private int _Time = 1000;
        private int _maxTime = 1000;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            _bucketTexture[0] = contentManager.Load<Texture2D>("bucket//bucket0");
            _bucketTexture[1] = contentManager.Load<Texture2D>("bucket//bucket1");
            _bucketTexture[2] = contentManager.Load<Texture2D>("bucket//bucket2");
            _bucketTexture[3] = contentManager.Load<Texture2D>("bucket//bucket3");
            _bucketTexture[4] = contentManager.Load<Texture2D>("bucket//bucket4");
            _bucketTexture[5] = contentManager.Load<Texture2D>("bucket//bucket5");
       
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            _grid = new Grid((int)(SharedGraphicsDeviceManager.DefaultBackBufferWidth ),(int) (SharedGraphicsDeviceManager.DefaultBackBufferHeight)-30,SharedGraphicsDeviceManager.Current.GraphicsDevice);

            if (null == elementRenderer)
            {
                elementRenderer = new UIElementRenderer(this, (int)SharedGraphicsDeviceManager.DefaultBackBufferWidth, (int)SharedGraphicsDeviceManager.DefaultBackBufferHeight);
            }

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
       
            TouchCollection touchCollection = TouchPanel.GetState();

            if (_Time > 0)
            {
                foreach (TouchLocation tl in touchCollection)
                {

                    if (tl.State == TouchLocationState.Moved)
                    {
                        if (tl.Position.Y < (int)SharedGraphicsDeviceManager.DefaultBackBufferHeight - 40)
                        {
                            _grid.SpawnSand(new Microsoft.Xna.Framework.Rectangle((int)(tl.Position.X * .25f) - (5 / 2), (int)(tl.Position.Y * .25f) - (5 / 2), 5, 5), 2);
                        }
                    }

                }

                _points += _grid.DeleteSandCount(_bucket, 1);
                if (_nextPointGoal - _points > 80)
                {
                    _bucketTextureIndex = 1;
                }
                else if (_nextPointGoal - _points > 60)
                {
                    _bucketTextureIndex = 2;
                }
                else if (_nextPointGoal - _points > 40)
                {
                    _bucketTextureIndex = 3;
                }
                else if (_nextPointGoal - _points > 20)
                {
                    _bucketTextureIndex = 4;
                }
                else
                {
                    _bucketTextureIndex = 5;
                }
            }

            if (_points > _nextPointGoal)
            {
                _grid.SpawnSand(new Rectangle((int)((_bucket.X - 5) * .25f), (int)((_bucket.Y - 5) * .25f), (int)((_bucket.Width + 5) * .25f), (int)((_bucket.Height + 5) * .25f)), 2);
                _bucketTextureIndex = 0;
                _bucket.X = _rand.Next(0, (SharedGraphicsDeviceManager.DefaultBackBufferWidth) - 40);
                _bucket.Y = _rand.Next(0, (SharedGraphicsDeviceManager.DefaultBackBufferHeight ) - 40);
                _nextPointGoal += 100;
                _maxTime -= 50;
                _Time = _maxTime;

            }
            _Time--;
          _grid.SpawnSand(new Microsoft.Xna.Framework.Rectangle((SharedGraphicsDeviceManager.DefaultBackBufferWidth /4)/2 , 2,2, 5), 1);
          _grid.SpawnSand(new Microsoft.Xna.Framework.Rectangle(0, ((SharedGraphicsDeviceManager.DefaultBackBufferHeight / 4) -15), SharedGraphicsDeviceManager.DefaultBackBufferWidth / 4, 15), 0);

              _grid.update();   
          
            _updateXamalInfo();
            
        }

        private void _updateXamalInfo()
        {
            if (_Time > 0)
            {
                TextPoint.Text = "Point:" + _points;
                TimeLeft.Text = "Time:" + _Time;
            }
            else
            {
                TextPoint.Text = "GAME OVER";
                TimeLeft.Text = "POINTS:"+_points;
                Write(_points);
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            elementRenderer.Render();

            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.White);
            spriteBatch.Begin();
            _grid.DrawTextureData(spriteBatch);
            spriteBatch.Draw(_bucketTexture[_bucketTextureIndex], new Vector2(_bucket.Left, _bucket.Top), Color.White);
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
          spriteBatch.End();
            // TODO: Add your drawing code here
        }

        private void Write(int score)
        {
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            using (var isoFileStream = new IsolatedStorageFileStream("score.txt", FileMode.OpenOrCreate, myStore))
            {
                // Write the data
                using (var isoFileWriter = new StreamWriter(isoFileStream))
                {
                    isoFileWriter.WriteLine(score.ToString());
                }
            }
        }


    }
}